<template>
  <div class="auth-container">
    <el-card class="auth-card summaries-card">
      <template #header>
        <div class="card-header">
          <h2>AI 摘要与报告</h2>
          <p class="subtitle">按日/周/月查看自动总结</p>
        </div>
      </template>

      <div class="toolbar">
        <el-select v-model="type" placeholder="类型" size="large" class="toolbar-item">
          <el-option label="每日" value="daily" />
          <el-option label="每周" value="weekly" />
          <el-option label="每月" value="monthly" />
        </el-select>
        <el-button 
          type="primary" 
          size="large" 
          @click="generateReport"
          :loading="loading || summariesStore.loading"
        >
          {{ loading || summariesStore.loading ? '生成中...' : '生成最新报告' }}
        </el-button>
      </div>

      <div v-if="summariesStore.loading" class="loading-container">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>加载中...</span>
      </div>

      <el-empty 
        v-else-if="!summariesStore.loading && filtered.length === 0" 
        description="暂无摘要数据，点击生成最新报告"
      />

      <el-timeline v-else>
        <el-timeline-item
          v-for="s in filtered"
          :key="s.id"
          :timestamp="fmt(s.created_at)"
          placement="top"
        >
          <el-card class="summary-card">
            <div class="summary-header">
              <el-tag type="success" size="small">{{ typeLabel(s.type) }}</el-tag>
              <span v-if="s.period_start" class="period-info">{{ s.period_start }}</span>
            </div>
            <div class="summary-content">{{ s.content || '暂无内容' }}</div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-card>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted } from 'vue'
  import { useSummariesStore, type SummaryType } from '@/stores/summaries'
  import { useUserStore } from '@/stores/auth/user'
  import { ElMessage } from 'element-plus'
  import { Loading } from '@element-plus/icons-vue'

  const summariesStore = useSummariesStore()
  const userStore = useUserStore()
  
  const type = ref<'daily'|'weekly'|'monthly'>('daily')
  const loading = ref(false)
  
  // 从 store 获取过滤后的列表
  const filtered = computed(() => {
    if (type.value === 'daily') return summariesStore.dailySummaries
    if (type.value === 'weekly') return summariesStore.weeklySummaries
    if (type.value === 'monthly') return summariesStore.monthlySummaries
    return []
  })
  
  function fmt(s: string) { 
    return new Date(s).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
  
  function typeLabel(t: SummaryType) {
    const labels: Record<SummaryType, string> = {
      daily: '每日',
      weekly: '每周',
      monthly: '每月',
      manual: '手动'
    }
    return labels[t] || t
  }
  
  async function generateReport() {
    const userId = userStore.getUserId
    if (!userId) {
      ElMessage.warning('请先登录')
      return
    }
    
    loading.value = true
    try {
      const now = new Date()
      let result
      
      if (type.value === 'daily') {
        const date = now.toISOString().split('T')[0] || '' // YYYY-MM-DD
        result = await summariesStore.fetchDailySummary(userId, date)
      } else if (type.value === 'weekly') {
        // 计算本周的周数，格式如 2025-W47
        const year = now.getFullYear()
        const firstDay = new Date(year, 0, 1)
        const days = Math.floor((now.getTime() - firstDay.getTime()) / (24 * 60 * 60 * 1000))
        const weekNumber = Math.ceil((days + firstDay.getDay() + 1) / 7)
        const week = `${year}-W${String(weekNumber).padStart(2, '0')}`
        result = await summariesStore.fetchWeeklySummary(userId, week)
      } else if (type.value === 'monthly') {
        const month = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}` // YYYY-MM
        result = await summariesStore.fetchMonthlySummary(userId, month)
      }
      
      if (result) {
        ElMessage.success('报告生成成功！')
      }
    } catch (error: any) {
      ElMessage.error(error.message || '生成报告失败')
    } finally {
      loading.value = false
    }
  }
  
  // 页面加载时获取最新的每日摘要
  onMounted(async () => {
    const userId = userStore.getUserId
    if (userId && !summariesStore.loaded) {
      try {
        const date = new Date().toISOString().split('T')[0] || ''
        await summariesStore.fetchDailySummary(userId, date)
      } catch (error) {
        console.error('加载摘要失败:', error)
      }
    }
  })

</script>

<style scoped>
.summaries-card { max-width: 900px; margin: 40px auto; }
.subtitle { margin: 6px 0 0; font-size: 14px; color: #8a6f5b; }
.toolbar { display: flex; gap: 12px; margin-bottom: 16px; }
.toolbar-item { min-width: 180px; }
.summary-card { background: #fffaf6; }
.summary-header { 
  display: flex; 
  align-items: center; 
  gap: 12px; 
  margin-bottom: 8px;
}
.period-info {
  font-size: 13px;
  color: #8a6f5b;
}
.summary-content { 
  color: #3d2b20; 
  white-space: pre-wrap; 
  line-height: 1.6;
}
.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 40px;
  color: #8a6f5b;
}
.is-loading {
  font-size: 24px;
  animation: rotating 1s linear infinite;
}
@keyframes rotating {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>